package com.example.beikeyigou.login_reg;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.beikeyigou.R;
import com.example.beikeyigou.dialog.ChangHeadDialog;
import com.example.beikeyigou.dialog.EditDialog;
import com.example.beikeyigou.utils.BaseActivity;
import com.example.beikeyigou.utils.SaveUserUtils;
import com.example.beikeyigou.utils.URLUtils;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

public class SelfDataChangeActivity extends BaseActivity {
    private UserBean.DataBean userData, newUserData;     // 之前登录时保存的用户信息

    private TextView idTv, nicknameTv, nameTv, addressTv;
    private ImageView backImg, userImg;

    String imgPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_self_data_change);

        findView();
        refreshData();
        changeStatusBarTextImgColor(true);
    }

    public void changeStatusBarTextImgColor(boolean color) {
        if (color) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//实现状态栏图标和文字颜色为暗色
        } else {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);//恢复状态栏白色字体
        }
    }

    // 更新当前控件所显示的值
    private void refreshData() {
        userData = SaveUserUtils.getUserData(this);
        if (userData == null) {
            idTv.setText("");
            nicknameTv.setText("");
            nameTv.setText("");
            addressTv.setText("");
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        if (userData.getId() == -1) {
            idTv.setText("");
            nicknameTv.setText("");
            nameTv.setText("");
            addressTv.setText("");
            return;
        }
        newUserData = new UserBean.DataBean(userData.getId(), userData.getPhone(),
                userData.getPassword(), userData.getName(), userData.getAddress(),
                userData.getNickname(), userData.getQuestion(), userData.getAnswer());
        imgPath = URLUtils.getImgPath(this, userData.getPhone());
        idTv.setText(String.valueOf(userData.getId()));
        nicknameTv.setText(userData.getNickname());
        nameTv.setText(userData.getName());
        // 设置“收货地址”的显示，当信息字符大于12时，将后面的信息折叠起来
        String address = userData.getAddress();
        String addressShow;
        if (address.length() > 12) {
            char[] temp = new char[15];
            address.getChars(0, 12, temp, 0);
            for (int i = 0; i < 3; ++i) {
                temp[12 + i] = '.';
            }
            addressShow = String.valueOf(temp);
        } else {
            addressShow = address;
        }
        addressTv.setText(addressShow);

        // 显示头像
        File file = new File(imgPath);
        if (file.exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
            userImg.setImageBitmap(bitmap);
        } else {
            userImg.setImageResource(R.mipmap.user);
        }
    }

    private void findView() {
        idTv = findViewById(R.id.dataChange_tv_tel);
        nicknameTv = findViewById(R.id.dataChange_tv_nickname);
        nameTv = findViewById(R.id.dataChange_tv_name);
        addressTv = findViewById(R.id.dataChange_tv_address);
        userImg = findViewById(R.id.dataChange_profilePic);
        backImg = findViewById(R.id.dataChange_back);
        backImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void onClickRelPic(View view) {
//        Toast.makeText(this, "头像", Toast.LENGTH_SHORT).show();
        ChangHeadDialog dialog = new ChangHeadDialog(this);
        dialog.show();
        dialog.setOnChangeHeadListener(new ChangHeadDialog.OnChangeHeadListener() {
            @Override
            public void clickCamera() {     // 跳转到相机
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent,100);
            }

            @Override
            public void clickLocal() {
                Intent intent = new Intent(SelfDataChangeActivity.this, LocalImgActivity.class);
                startActivityForResult(intent,200);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode==100) {
            Bundle bundle = data.getExtras();
            Bitmap bm = (Bitmap) bundle.get("data");
            userImg.setImageBitmap(bm);
            saveBitmap(bm);
        }
        if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
            String fPath = data.getStringExtra("fPath");
            Bitmap bitmap = BitmapFactory.decodeFile(fPath);
            userImg.setImageBitmap(bitmap);
            saveBitmap(bitmap);
        }
    }

    // 将照片保存下来
    private void saveBitmap(Bitmap bm) {
        try {
            FileOutputStream fos = new FileOutputStream(imgPath);
            bm.compress(Bitmap.CompressFormat.JPEG,80,fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void onClickRelNickName(View view) {
        showDialog(editDialog.Nickname);
    }

    public void onClickRelName(View view) {
        showDialog(editDialog.Name);
    }

    public void onClickRelAddress(View view) {
        showDialog(editDialog.Address);
    }

    private enum editDialog {
        Nickname, Name, Address
    }

    // 显示对话框
    private void showDialog(editDialog select) {
        EditDialog dialog = new EditDialog(this);
        dialog.show();
        switch (select) {
            case Nickname:
                dialog.setMyTitle("贝壳昵称")
                        .setEditText(userData.getNickname())
                        .setOnClickBottomListener(new EditDialog.OnClickBottomListener() {
                            @Override
                            public void onPositiveClick() {
                                String nickname = dialog.getEditText();
                                if (!nickname.equals("")) {
                                    newUserData.setNickname(nickname);
                                    Map<String, String> map = new HashMap<>();
                                    map.put("id", String.valueOf(newUserData.getId()));
                                    map.put("address", newUserData.getAddress());
                                    map.put("nickname", newUserData.getNickname());
                                    map.put("name", newUserData.getName());
                                    postNetwork(URLUtils.updateInfo_url, map);          // 修改服务器数据
                                }
                                dialog.dismiss();
                            }
                            @Override
                            public void onNegtiveClick() {
                                dialog.dismiss();
                            }
                        });
                break;
            case Name:
                dialog.setMyTitle("收货人姓名")
                        .setEditText(userData.getName())
                        .setOnClickBottomListener(new EditDialog.OnClickBottomListener() {
                            @Override
                            public void onPositiveClick() {
                                String Name = dialog.getEditText();
                                if (!Name.equals("")) {
                                    newUserData.setName(Name);
                                    Map<String, String> map = new HashMap<>();
                                    map.put("id", String.valueOf(newUserData.getId()));
                                    map.put("address", newUserData.getAddress());
                                    map.put("nickname", newUserData.getNickname());
                                    map.put("name", newUserData.getName());
                                    postNetwork(URLUtils.updateInfo_url, map);          // 修改服务器数据
                                }
                                dialog.dismiss();
                            }
                            @Override
                            public void onNegtiveClick() {
                                dialog.dismiss();
                            }
                        });
                break;
            case Address:
                dialog.setMyTitle("收货地址")
                        .setEditText(userData.getAddress())
                        .setOnClickBottomListener(new EditDialog.OnClickBottomListener() {
                            @Override
                            public void onPositiveClick() {
                                String Address = dialog.getEditText();
                                if (!Address.equals("")) {
                                    newUserData.setAddress(Address);
                                    Map<String, String> map = new HashMap<>();
                                    map.put("id", String.valueOf(newUserData.getId()));
                                    map.put("address", newUserData.getAddress());
                                    map.put("nickname", newUserData.getNickname());
                                    map.put("name", newUserData.getName());
                                    postNetwork(URLUtils.updateInfo_url, map);          // 修改服务器数据
                                }
                                dialog.dismiss();
                            }
                            @Override
                            public void onNegtiveClick() {
                                dialog.dismiss();
                            }
                        });
                break;
        }
    }

    @Override
    public void onSuccess(String result) {
        super.onSuccess(result);
        // 解析数据
        UserBean bean = new Gson().fromJson(result, UserBean.class);
        int code = bean.getCode();
        switch (code) {
            case 200:       // 修改成功
                Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
                // 保存修改信息
                SaveUserUtils.saveUserToFile(this, newUserData);
                refreshData();
                break;
            default:        // 其他，修改失败
                Toast.makeText(this, "修改失败", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }
}